Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dog_images.

  • Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [1]:
import numpy as np
from glob import glob

# load filenames for human and dog images
human_files = np.array(glob("/data/lfw/*/*"))
dog_files = np.array(glob("/data/dog_images/*/*/*"))

# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
There are 13233 total human images.
There are 8351 total dog images.
In [2]:
human_files[0]
Out[2]:
'/data/lfw/Dan_Ackroyd/Dan_Ackroyd_0001.jpg'

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: (You can print out your results and/or write your percentages in this cell)

In [5]:
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

def perc_detected(images):
    
    for i in tqdm(range(len(images))):
        face_detector_res = np.array([face_detector(image) for image in images])
    perc_detected = np.sum(face_detector_res)/len(face_detector_res) * 100
    
    return perc_detected


print('percentage of human images with a detected face: {}%'.format(perc_detected(human_files_short)))
print('percentage of dog images with a detected face: {}%'.format(perc_detected(dog_files_short)))    
100%|██████████| 100/100 [04:38<00:00,  2.79s/it]
  0%|          | 0/100 [00:00<?, ?it/s]
percentage of human images with a detected face: 98.0%
100%|██████████| 100/100 [49:26<00:00, 29.72s/it]
percentage of dog images with a detected face: 17.0%

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [ ]:
### (Optional) 
### TODO: Test performance of anotherface detection algorithm.
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [5]:
import torch
import torchvision.models as models

# define VGG16 model
VGG16 = models.vgg16(pretrained=True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()

# move model to GPU if CUDA is available
if use_cuda:
    VGG16 = VGG16.cuda()

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

Getting a idea about the distributuin of height and width of the images

In [38]:
#All pre-trained models expect input images normalized in the same way, 
#i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), 
#where H and W are expected to be at least 224. 
#The images have to be loaded in to a range of [0, 1] 
#and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225]. 


from PIL import Image

image_width = []
image_height = []
for img_path in dog_files:
    image_width.append(Image.open(img_path).size[0])
    image_height.append(Image.open(img_path).size[1])
    
width = np.array(image_width)
height = np.array(image_height)
In [39]:
plt.hist(width);
plt.title("Images' width distribution");
In [40]:
plt.hist(height);
plt.title("Images' height distribution");
In [6]:
#https://pytorch.org/docs/stable/torchvision/transforms.html
#stride error
#https://discuss.pytorch.org/t/expected-stride-to-be-a-single-integer-value-or-a-list/17612/4
#transforms part
#https://www.kaggle.com/carloalbertobarbano/vgg16-transfer-learning-pytorch

from PIL import Image
import torchvision.transforms as transforms

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]


def VGG16_predict(img_path):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    
    ## TODO: Complete the function.
    ## Load and pre-process an image from the given img_path
    ## Return the *index* of the predicted class for that image
    
    
        
    transform = transforms.Compose([
                    transforms.Resize(256),
                    transforms.CenterCrop(224),
                    transforms.ToTensor(),
                    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225])
                    ])
    
    # load the image as RGB
    img = Image.open(img_path).convert('RGB')

    # preprocess the image and transform it to tensor   
    preprocessed_img = transform(img)
    
    batch = torch.unsqueeze(preprocessed_img, 0)
    if use_cuda:
        batch = batch.to('cuda')
        
    # output of the VGG16 Classification
    VGG16.eval()
    output = VGG16(batch)
    
    # index of the predicted class
    
    max_val,index = torch.max(output, dim=1)
    
    
    
    return index.item() # predicted class index

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [7]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    ## TODO: Complete the function.
    
    pred_idx = VGG16_predict(img_path)
    
    if  151 <= pred_idx <= 268:
        is_dog = True
    else:
        is_dog = False
    
    return is_dog # true/false

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:
percentage of human images detected as dogs: 0%
percentage of dog images detected as dogs: 100%

In [43]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
from tqdm import tqdm

def perc_detected(images):
    
    for i in tqdm(range(len(images))):
        dog_detector_res = np.array([dog_detector(image) for image in images])
    perc_detected = np.sum(dog_detector_res)/len(dog_detector_res) * 100
    
    return perc_detected


print('percentage of human images detected as dogs: {}%'.format(perc_detected(human_files_short)))
print('percentage of dog images detected as dogs: {}%'.format(perc_detected(dog_files_short)))   
100%|██████████| 100/100 [05:03<00:00,  3.02s/it]
  0%|          | 0/100 [00:00<?, ?it/s]
percentage of human images detected as dogs: 0.0%
100%|██████████| 100/100 [07:35<00:00,  4.54s/it]
percentage of dog images detected as dogs: 100.0%

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [ ]:
### (Optional) 
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dog_images/train, dog_images/valid, and dog_images/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [8]:
import os
from torchvision import datasets

### TODO: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes

bs=64
data_transform =  { 
    'train': transforms.Compose([
                       transforms.RandomHorizontalFlip(),
                       transforms.RandomRotation(20),
                       transforms.RandomResizedCrop(224),
                       transforms.ToTensor(),
                       transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225])
            ]),
 
     'valid': transforms.Compose([
                       transforms.Resize(256),
                       transforms.CenterCrop(224),
                       transforms.ToTensor(),
                       transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225])
     ]),

     'test': transforms.Compose([
                      transforms.Resize(256),
                      transforms.CenterCrop(224),
                      transforms.ToTensor(),
                      transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225])
     ]),
  }
    
root_path = '/data/dog_images/'

images_data = { x : datasets.ImageFolder(os.path.join(root_path, x), transform = data_transform[x] )
                      for x in ['train', 'valid', 'test'] 
               }

print(images_data)


loaders_scratch = { x : torch.utils.data.DataLoader(images_data[x], batch_size= bs, shuffle=True, num_workers=0)
                   for x in ['train', 'valid', 'test']
                  }


print(loaders_scratch)
{'train': Dataset ImageFolder
    Number of datapoints: 6680
    Root Location: /data/dog_images/train
    Transforms (if any): Compose(
                             RandomHorizontalFlip(p=0.5)
                             RandomRotation(degrees=(-20, 20), resample=False, expand=False)
                             RandomResizedCrop(size=(224, 224), scale=(0.08, 1.0), ratio=(0.75, 1.3333), interpolation=PIL.Image.BILINEAR)
                             ToTensor()
                             Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
                         )
    Target Transforms (if any): None, 'valid': Dataset ImageFolder
    Number of datapoints: 835
    Root Location: /data/dog_images/valid
    Transforms (if any): Compose(
                             Resize(size=256, interpolation=PIL.Image.BILINEAR)
                             CenterCrop(size=(224, 224))
                             ToTensor()
                             Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
                         )
    Target Transforms (if any): None, 'test': Dataset ImageFolder
    Number of datapoints: 836
    Root Location: /data/dog_images/test
    Transforms (if any): Compose(
                             Resize(size=256, interpolation=PIL.Image.BILINEAR)
                             CenterCrop(size=(224, 224))
                             ToTensor()
                             Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
                         )
    Target Transforms (if any): None}
{'train': <torch.utils.data.dataloader.DataLoader object at 0x7f3fae51fc18>, 'valid': <torch.utils.data.dataloader.DataLoader object at 0x7f3fae51fdd8>, 'test': <torch.utils.data.dataloader.DataLoader object at 0x7f3fae51fe48>}

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?

Answer:

  • The images were resized by cropping. The input tensor has a shape of (3 x H x W) with 3 for RGB channels and 224x224 for Height and Width. Since VGG16 model was originally trained on the 224x224 resolution
  • Yes, the data was augmented through random horizontal flips and 20 degree rotations

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

In [9]:
import torch.nn as nn
import torch.nn.functional as F

# define the CNN architecture
class Net(nn.Module):
    ### TODO: choose an architecture, and complete the class
    def __init__(self):
        super(Net, self).__init__()
        ## Define layers of a CNN
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)
        self.bnorm1 = nn.BatchNorm2d(16)
        self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1)
        self.bnorm2 = nn.BatchNorm2d(32)
        self.conv3 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
        self.bnorm3 = nn.BatchNorm2d(64)
        self.conv4 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
        self.bnorm4 = nn.BatchNorm2d(128)
        
        self.fc1 = nn.Linear(128*14*14, 1024)
        self.fc2 = nn.Linear(1024, len(images_data['train'].classes))
     
        self.dropout2d = nn.Dropout2d(0.5)
        self.dropout = nn.Dropout(0.2)
        self.pool = nn.MaxPool2d(2,2)
        
    
    def forward(self, x):
        ## Define forward behavior
        x = self.pool(F.relu(self.conv1(x)))
        x = self.bnorm1(x)
        x = self.pool(F.relu(self.conv2(x)))
        x = self.bnorm2(x)
        x = self.pool(F.relu(self.conv3(x)))
        x = self.bnorm3(x)
        x = self.pool(F.relu(self.conv4(x)))
        x = self.bnorm4(x)
        
        # here x shape is [20, 128, 14, 14]
        
        x = x.view(x.size(0), -1)
       
        x = self.dropout(F.relu(self.fc1(x)))
        x = self.fc2(x)
    
        return x

#-#-# You so NOT have to modify the code below this line. #-#-#

# instantiate the CNN
model_scratch = Net()
print(model_scratch)

# move tensors to GPU if CUDA is available
if use_cuda:
    model_scratch.cuda()
Net(
  (conv1): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (bnorm1): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (conv2): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (bnorm2): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (conv3): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (bnorm3): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (conv4): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (bnorm4): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (fc1): Linear(in_features=25088, out_features=1024, bias=True)
  (fc2): Linear(in_features=1024, out_features=133, bias=True)
  (dropout2d): Dropout2d(p=0.5)
  (dropout): Dropout(p=0.2)
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

Answer:

First of all I did a google search to get some idea about the number of layers in other CNN architecture used to classify similar dataset and I found in the below, that 3 Conv Layers were used:

https://medium.com/nanonets/how-to-easily-build-a-dog-breed-image-classification-model-2fd214419cde

so I have created 4 Convolutional layers with kernel size 3x3 stride=1 and padding=1 to get the same image size as output, and those Conv Layers were stacked with pooling layers with the aim to reduce the size by 2 while maintaining the depth of the preceding Conv layer output.

I thought that the dog breed classification is somehow a complex problem and I tried with to increase the output channels for each of the Conv Layers going from 16 up to 128 in the hope to learn the necessary low level features:

  • conv1 input 3 output 16
  • ReLU
  • Maxpooling

  • conv2 input 16 output 32

  • ReLU
  • Maxpooling

  • conv3 input 32 output 64

  • ReLU
  • Maxpooling

  • conv4 input 64 output 128

  • ReLU
  • Maxpooling

Then I added 3 Fully connected layers, with a Dropout layer with probability of 0.2 in between with the aim to improve generalization.

  • The First linear layer had an input 128x14x14 (number of channelsx height x width) and output 128
  • The second Linear Layer had an input of 128 and oupt 256
  • The third Linear Layer of input of 256 and an output the number of classes 133.

But with the above I was not able to get below 4.8 training loss, so I referred to posts from mentors on student Hub advising students to add Batch normalization layers, so I added 4 Batch normalization layers after to ouptut of each of the ReLU,Conv and Pooling layers. But again I could not get better results.

So I noticed that Fully Connected Layer had a high number of inputs 128x14x14, I decided to increase the number of nodes in the Linear Layer to 1024, so I reduced the Linear Layers from 3 to 2:

  • The First linear layer have an input 128x14x14 (number of channelsx height x width) and output of 1024
  • The Second Linear Layer input of 1024 and output the number of classes.

This is where I started to see improvements and the Training Loss started to decrease.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [10]:
import torch.optim as optim

### TODO: select loss function
criterion_scratch = nn.CrossEntropyLoss()

### TODO: select optimizer
optimizer_scratch = optim.Adam(model_scratch.parameters(), lr = 0.001)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [11]:
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

import time

valid_losses = [] 
train_losses = []

def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
    """returns trained model"""
    # initialize tracker for minimum validation loss
    valid_loss_min = np.Inf 
    
    
    
    for epoch in range(1, n_epochs+1):
        start_time = time.time() 
        # initialize variables to monitor training and validation loss
        train_loss = 0.0
        valid_loss = 0.0
        correct = 0.0
        
        ###################
        # train the model #
        ###################
        model.train()
        for batch_idx, (data, target) in enumerate(loaders['train']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            optimizer.zero_grad()
            # forward
            #print (data.size())
            output = model(data)
            loss = criterion(output, target)
            # backpropagation
            loss.backward()
            optimizer.step()
            ## find the loss and update the model parameters accordingly
            ## record the average training loss, using something like
            train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
            
        ######################    
        # validate the model #
        ######################
        model.eval()
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## update the average validation loss
            # forward
            with torch.no_grad():
                outputs = model(data)
                loss = criterion(outputs, target)
                ## record the average validation loss, using something like
                valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
                
        valid_losses.append(valid_loss)
        train_losses.append(train_losses)
        
        # print time taken
        
        print('epoch training time: {:.2f}'.format(time.time() - start_time))
        # print training/validation statistics 
        print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
            epoch, 
            train_loss,
            valid_loss
            ))
        
        ## TODO: save the model if validation loss has decreased
        if valid_loss <= valid_loss_min:
            print('Validation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(
            valid_loss_min, valid_loss))
            
            torch.save(model.state_dict(), save_path)
            
            valid_loss_min = valid_loss
    # return trained model
    return model
In [42]:
# train the model
model_scratch = train(100, loaders_scratch, model_scratch, optimizer_scratch, 
                      criterion_scratch, use_cuda, 'model_scratch.pt')

# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
epoch training time: 114.16
Epoch: 1 	Training Loss: 5.107552 	Validation Loss: 4.640107
Validation loss decreased (inf --> 4.640107).  Saving model ...
epoch training time: 97.38
Epoch: 2 	Training Loss: 4.620212 	Validation Loss: 4.373680
Validation loss decreased (4.640107 --> 4.373680).  Saving model ...
epoch training time: 97.87
Epoch: 3 	Training Loss: 4.484685 	Validation Loss: 4.111014
Validation loss decreased (4.373680 --> 4.111014).  Saving model ...
epoch training time: 97.83
Epoch: 4 	Training Loss: 4.340325 	Validation Loss: 4.098918
Validation loss decreased (4.111014 --> 4.098918).  Saving model ...
epoch training time: 97.62
Epoch: 5 	Training Loss: 4.239075 	Validation Loss: 4.169853
epoch training time: 97.88
Epoch: 6 	Training Loss: 4.127082 	Validation Loss: 3.970937
Validation loss decreased (4.098918 --> 3.970937).  Saving model ...
epoch training time: 97.86
Epoch: 7 	Training Loss: 4.035941 	Validation Loss: 3.891049
Validation loss decreased (3.970937 --> 3.891049).  Saving model ...
epoch training time: 98.86
Epoch: 8 	Training Loss: 3.894805 	Validation Loss: 3.749152
Validation loss decreased (3.891049 --> 3.749152).  Saving model ...
epoch training time: 98.07
Epoch: 9 	Training Loss: 3.837367 	Validation Loss: 3.687875
Validation loss decreased (3.749152 --> 3.687875).  Saving model ...
epoch training time: 98.29
Epoch: 10 	Training Loss: 3.734824 	Validation Loss: 3.539293
Validation loss decreased (3.687875 --> 3.539293).  Saving model ...
epoch training time: 98.40
Epoch: 11 	Training Loss: 3.660862 	Validation Loss: 3.579089
epoch training time: 97.80
Epoch: 12 	Training Loss: 3.608281 	Validation Loss: 3.489126
Validation loss decreased (3.539293 --> 3.489126).  Saving model ...
epoch training time: 98.60
Epoch: 13 	Training Loss: 3.520868 	Validation Loss: 3.465066
Validation loss decreased (3.489126 --> 3.465066).  Saving model ...
epoch training time: 97.76
Epoch: 14 	Training Loss: 3.484871 	Validation Loss: 3.367368
Validation loss decreased (3.465066 --> 3.367368).  Saving model ...
epoch training time: 98.40
Epoch: 15 	Training Loss: 3.430845 	Validation Loss: 3.348628
Validation loss decreased (3.367368 --> 3.348628).  Saving model ...
epoch training time: 98.22
Epoch: 16 	Training Loss: 3.355079 	Validation Loss: 3.263570
Validation loss decreased (3.348628 --> 3.263570).  Saving model ...
epoch training time: 98.19
Epoch: 17 	Training Loss: 3.328740 	Validation Loss: 3.242721
Validation loss decreased (3.263570 --> 3.242721).  Saving model ...
epoch training time: 97.98
Epoch: 18 	Training Loss: 3.247555 	Validation Loss: 3.161468
Validation loss decreased (3.242721 --> 3.161468).  Saving model ...
epoch training time: 97.59
Epoch: 19 	Training Loss: 3.200286 	Validation Loss: 3.140801
Validation loss decreased (3.161468 --> 3.140801).  Saving model ...
epoch training time: 97.69
Epoch: 20 	Training Loss: 3.150651 	Validation Loss: 3.029245
Validation loss decreased (3.140801 --> 3.029245).  Saving model ...
epoch training time: 96.64
Epoch: 21 	Training Loss: 3.135546 	Validation Loss: 3.196161
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-42-c0d3078ebe65> in <module>()
      1 # train the model
      2 model_scratch = train(100, loaders_scratch, model_scratch, optimizer_scratch, 
----> 3                       criterion_scratch, use_cuda, 'model_scratch.pt')
      4 
      5 # load the model that got the best validation accuracy

<ipython-input-14-4e5b66394a13> in train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path)
     25         ###################
     26         model.train()
---> 27         for batch_idx, (data, target) in enumerate(loaders['train']):
     28             # move to GPU
     29             if use_cuda:

/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py in __next__(self)
    262         if self.num_workers == 0:  # same-process loading
    263             indices = next(self.sample_iter)  # may raise StopIteration
--> 264             batch = self.collate_fn([self.dataset[i] for i in indices])
    265             if self.pin_memory:
    266                 batch = pin_memory_batch(batch)

/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py in <listcomp>(.0)
    262         if self.num_workers == 0:  # same-process loading
    263             indices = next(self.sample_iter)  # may raise StopIteration
--> 264             batch = self.collate_fn([self.dataset[i] for i in indices])
    265             if self.pin_memory:
    266                 batch = pin_memory_batch(batch)

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/datasets/folder.py in __getitem__(self, index)
    101         sample = self.loader(path)
    102         if self.transform is not None:
--> 103             sample = self.transform(sample)
    104         if self.target_transform is not None:
    105             target = self.target_transform(target)

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/transforms.py in __call__(self, img)
     47     def __call__(self, img):
     48         for t in self.transforms:
---> 49             img = t(img)
     50         return img
     51 

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/transforms.py in __call__(self, img)
    820         angle = self.get_params(self.degrees)
    821 
--> 822         return F.rotate(img, angle, self.resample, self.expand, self.center)
    823 
    824     def __repr__(self):

/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/functional.py in rotate(img, angle, resample, expand, center)
    593         raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
    594 
--> 595     return img.rotate(angle, resample, expand, center)
    596 
    597 

/opt/conda/lib/python3.6/site-packages/PIL/Image.py in rotate(self, angle, resample, expand, center, translate, fillcolor)
   1869             w, h = nw, nh
   1870 
-> 1871         return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)
   1872 
   1873     def save(self, fp, format=None, **params):

/opt/conda/lib/python3.6/site-packages/PIL/Image.py in transform(self, size, method, data, resample, fill, fillcolor)
   2167         else:
   2168             im.__transformer((0, 0)+size, self, method, data,
-> 2169                              resample, fillcolor is None)
   2170 
   2171         return im

/opt/conda/lib/python3.6/site-packages/PIL/Image.py in __transformer(self, box, image, method, data, resample, fill)
   2218             resample = NEAREST
   2219 
-> 2220         self.im.transform2(box, image.im, method, data, resample, fill)
   2221 
   2222     def transpose(self, method):

KeyboardInterrupt: 

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [12]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        
        # move to GPU
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        # calculate the loss
        loss = criterion(output, target)
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        # compare predictions to true label
        
        
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
        
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))
    
In [14]:
# call test function    
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
Test Loss: 3.203951


Test Accuracy: 23% (197/836)
<built-in method size of Tensor object at 0x7f5f5f832708>

Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [13]:
## TODO: Specify data loaders
#https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy
loaders_transfer = loaders_scratch.copy()

print (loaders_transfer)
{'train': <torch.utils.data.dataloader.DataLoader object at 0x7f3fae51fc18>, 'valid': <torch.utils.data.dataloader.DataLoader object at 0x7f3fae51fdd8>, 'test': <torch.utils.data.dataloader.DataLoader object at 0x7f3fae51fe48>}

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

In [14]:
import torchvision.models as models
import torch.nn as nn

#https://pytorch.org/docs/stable/notes/autograd.html
#https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html
## TODO: Specify model architecture 


vgg = models.vgg16(pretrained=True)

# freezing the weight update for the pre-trained model
for param in vgg.parameters():
    param.requires_grad = False
    
# check the Fully connected layers of the vgg16 model


print(vgg.classifier)

# Replace the last FC layer with a new one with output
# features = 133

n_inputs = vgg.classifier[6].in_features

n_classes = len(images_data['train'].classes)

last_layer = nn.Linear(n_inputs, n_classes)

vgg.classifier[6] = last_layer

print(vgg.classifier)

model_transfer = vgg


if use_cuda:
    model_transfer = model_transfer.cuda()
Sequential(
  (0): Linear(in_features=25088, out_features=4096, bias=True)
  (1): ReLU(inplace)
  (2): Dropout(p=0.5)
  (3): Linear(in_features=4096, out_features=4096, bias=True)
  (4): ReLU(inplace)
  (5): Dropout(p=0.5)
  (6): Linear(in_features=4096, out_features=1000, bias=True)
)
Sequential(
  (0): Linear(in_features=25088, out_features=4096, bias=True)
  (1): ReLU(inplace)
  (2): Dropout(p=0.5)
  (3): Linear(in_features=4096, out_features=4096, bias=True)
  (4): ReLU(inplace)
  (5): Dropout(p=0.5)
  (6): Linear(in_features=4096, out_features=133, bias=True)
)

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

  • Used the VGG16 Model with the pretrained Weights on the ImageNet dataset
  • decided to Freeze all the Network layers (features and classifiers)
  • Replaced the final Fully connected Layer to have the output features = 133 to match the classes of the dog breed dataset, as the VGG16 was trained to classify 1000 categories
  • Adding the output layer would by default set the autograd = True, thus the final Layer weights can be updated with the training unlike the rest of the layers Features and classfiers

The dog breed dataset we have is considered small but similar to the one with which VGG16 Model was orginally trained, thus freezing the weights of all the VGG16 layers, would help in recognizing the features available in the Dog images without overfitting, while updating the weights of the last layer is good in order to classify the dog breeds based on 133 classes available.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [15]:
lr = 0.001
criterion_transfer = nn.CrossEntropyLoss()
optimizer_transfer = optim.SGD(vgg.classifier[6].parameters(), lr=lr, momentum=0.9)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

In [ ]:
# train the model
import matplotlib.pyplot as plt  

model_transfer = train(15, loaders_transfer,
                       model_transfer, optimizer_transfer, 
                       criterion_transfer, use_cuda, 'model_transfer.pt')
    
plt.plot(train_losses, label='Training loss')
plt.plot(valid_losses, label='Validation loss')
plt.xlabel('epochs')
plt.ylabel('losses')
epoch training time: 101.94
Epoch: 1 	Training Loss: 3.596953 	Validation Loss: 1.785426
Validation loss decreased (inf --> 1.785426).  Saving model ...
epoch training time: 102.06
Epoch: 2 	Training Loss: 1.982899 	Validation Loss: 1.077719
Validation loss decreased (1.785426 --> 1.077719).  Saving model ...
epoch training time: 102.18
Epoch: 3 	Training Loss: 1.576770 	Validation Loss: 0.854004
Validation loss decreased (1.077719 --> 0.854004).  Saving model ...
epoch training time: 101.78
Epoch: 4 	Training Loss: 1.385920 	Validation Loss: 0.707534
Validation loss decreased (0.854004 --> 0.707534).  Saving model ...
epoch training time: 101.33
Epoch: 5 	Training Loss: 1.289157 	Validation Loss: 0.591109
Validation loss decreased (0.707534 --> 0.591109).  Saving model ...
epoch training time: 102.03
Epoch: 6 	Training Loss: 1.176843 	Validation Loss: 0.601844
epoch training time: 102.73
Epoch: 7 	Training Loss: 1.131741 	Validation Loss: 0.533391
Validation loss decreased (0.591109 --> 0.533391).  Saving model ...
epoch training time: 102.02
Epoch: 8 	Training Loss: 1.092405 	Validation Loss: 0.548134
epoch training time: 102.16
Epoch: 9 	Training Loss: 1.064710 	Validation Loss: 0.482121
Validation loss decreased (0.533391 --> 0.482121).  Saving model ...
epoch training time: 102.03
Epoch: 10 	Training Loss: 1.026484 	Validation Loss: 0.476001
Validation loss decreased (0.482121 --> 0.476001).  Saving model ...
epoch training time: 103.36
Epoch: 11 	Training Loss: 1.028668 	Validation Loss: 0.444905
Validation loss decreased (0.476001 --> 0.444905).  Saving model ...
epoch training time: 102.15
Epoch: 12 	Training Loss: 0.958923 	Validation Loss: 0.453927
epoch training time: 103.05
Epoch: 13 	Training Loss: 0.979330 	Validation Loss: 0.418575
Validation loss decreased (0.444905 --> 0.418575).  Saving model ...
epoch training time: 103.14
Epoch: 14 	Training Loss: 0.956919 	Validation Loss: 0.414385
Validation loss decreased (0.418575 --> 0.414385).  Saving model ...

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [16]:
# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
In [17]:
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
Test Loss: 0.439757


Test Accuracy: 86% (719/836)

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [18]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
import os

# list of class names by index, i.e. a name can be accessed like class_names[0]
class_names = [item[4:].replace("_", " ") for item in images_data['train'].classes]


def predict_breed_transfer(img_path):
    
    # load the image and return the predicted breed
    transform = transforms.Compose([
                transforms.Resize(256),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                transforms.Normalize(mean=[0.485, 0.456, 0.406],
                        std=[0.229, 0.224, 0.225])])
    
    img = Image.open(img_path).convert('RGB')
    preprocessed_img = transform(img)
    tensor_image = preprocessed_img[:3,:,:].unsqueeze(0)
    
    #https://medium.com/datadriveninvestor/deploy-your-pytorch-model-to-production-f69460192217

    model_transfer.cpu()
    model_transfer.eval()
    
    output = model_transfer(tensor_image)
    index = torch.max(output.data, dim=1)[1]
        
    return class_names[index]
   

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and human_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [19]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def run_app(img_path):
    orig_img = Image.open(img_path)
    ## handle cases for a human face, dog, and neither
    if face_detector(img_path):
       
        breed = predict_breed_transfer(img_path)
        
        plt.figure()
        plt.imshow(orig_img)
        plt.title('Human detected!')
        plt.suptitle("You look like a {} !".format(breed), y=-0.001)
        
    elif dog_detector(img_path):
        
        breed = predict_breed_transfer(img_path)
        
        plt.figure()
        plt.imshow(orig_img)
        plt.title('Dog detected!')
        plt.suptitle("Predicted dog breed: {}".format(breed), y=-0.001)
    
    else:
        plt.figure()
        plt.imshow(orig_img)
        plt.title('Could not detect a Human nor Dog!')
        

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: Yes actually the output is better than I expected for example the wolf was not mistakenly detected as a dog the same for the plush, though there is room for improvements. It looks like the Human detector is not trained enough to recognize human with dark skin.

Also dog breeds classifier is sometimes not able to distinguish between some of the dog breed that look-alikes.
For instance predicited English coker spaniel while actually it is cocker spaniel.

In order to improve the classifier:

In [20]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

## suggested code, below
for file in np.hstack((human_files[:3], dog_files[:3])):
    run_app(file)
    
In [21]:
new_images_path = np.array(glob('/home/workspace/dog_project/images/*'))

for image_path in new_images_path:
    run_app(image_path)
In [22]:
new_images_path = np.array(glob('/home/workspace/dog_project/images_fb/*'))
for image_path in new_images_path:
    run_app(image_path)
In [23]:
# taken from udacity class
# helper function for un-normalizing an image 
# and converting it from a Tensor image to a NumPy image for display
def im_convert(tensor):
    """ Display a tensor as an image. """
    
    image = tensor.to("cpu").clone().detach()
    image = image.numpy().squeeze()
    image = image.transpose(1,2,0)
    image = image * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406))
    image = image.clip(0, 1)
    
    return image
In [24]:
# function to plot misclassifed images

def plot_missclassified(images, target):
    
    '''function to plot misclassified images'''
    
    for num, image in enumerate(images):
        output = model_transfer(image.unsqueeze(0))
        tensor_to_image = im_convert(image)
   
        index = torch.max(output.data, dim=1)[1]
        if (int(target[num]) != index.item()):
            target_classname = class_names[int(target[num])]
            predicted_classname = class_names[index]
            plt.figure()
            plt.imshow(tensor_to_image)
            plt.title(f'predicted: {predicted_classname}, actual: {target_classname}')
        
        
        
In [27]:
dataiter = iter(loaders_transfer['test'])
images, target = dataiter.next()
In [28]:
plot_missclassified(images, target)